package titt.server.service.db;

import java.util.ArrayList;
import java.util.Collections;

import titt.key.TITTKey;
import titt.server.service.Service;

public class ServerDatabaseImpl implements ServerDatabase {

	private ArrayList<Service> serviceList = new ArrayList<Service>();
	
	public synchronized boolean containsDuplicateKey(TITTKey key) {
		for(Service s : serviceList)
			if(s.getKey().equals(key))
				return true;
		return false;
	}
	
	public synchronized void add(Service s) {
		serviceList.add(s);
		
		Collections.sort(serviceList);
	}
	
	public synchronized Service remove(String id) {
		int index = getIndex(id);

		if(index == -1)
			return null;
		
		return serviceList.remove(index);
	}
	
	private synchronized int getIndex(String id) {
		for(int i = 0; i < serviceList.size(); i++) 
			if(serviceList.get(i).getID().equals(id))
				return i;
		return -1;
	}
	
	public synchronized Service get(String id) {
		int index = getIndex(id);

		if(index == -1)
			return null;
		
		return serviceList.get(index);
		
	}
	
	public synchronized Service get(TITTKey key) {
		
		for(Service s : serviceList)
			if(s.getKey().asKeyString().equals(key.asKeyString()))
				return s;
		
		for(Service s : serviceList)
			if(s.getKey().equivalentTo(key))
				return s;

		return null;
	}
	
	public synchronized Service[] getAll() {
		Service[] ret = new Service[serviceList.size()];
		ret = serviceList.toArray(ret);
		return ret;
	}
	
}
